package com.xm.bluetoothkotlin.receiver

import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.xm.bluetoothkotlin.BluetoothManager

/**
 * @创建者:小垚
 * @时间:2021/11/11
 *@描述: 蓝牙广播
 */
class BluetoothReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        intent?.run {
            if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
                when (getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) {
                    BluetoothAdapter.STATE_OFF -> {
                        //蓝牙已关闭
                        notifyCloseBluetooth()
                    }
                    BluetoothAdapter.STATE_ON -> {
                        //蓝牙已开启
                        notifyOpenBluetooth()
                    }
                    BluetoothAdapter.STATE_TURNING_ON -> {
                        //正在打开蓝牙
                        notifyOpenContinueBluetooth()
                    }
                    BluetoothAdapter.STATE_TURNING_OFF -> {
                        //正在关闭蓝牙
                        notifyCloseContinueBluetooth()
                    }
                    else -> {
                        //未知状态
                        notifyOnErrorBluetooth()
                    }
                }
            }
        }
    }

    /**
     * 通知蓝牙已打开
     */
    private fun notifyOpenBluetooth() {
        BluetoothManager.receivers.forEachIndexed { index, receiverCallBack ->
            receiverCallBack.openBluetooth()
        }
    }

    /**
     * 通知蓝牙已关闭
     */
    private fun notifyCloseBluetooth() {
        BluetoothManager.receivers.forEachIndexed { index, receiverCallBack ->
            BluetoothManager.destroy()
            receiverCallBack.closeBluetooth()
        }
    }

    /**
     * 通知蓝牙正在打开蓝牙
     */
    private fun notifyOpenContinueBluetooth() {
        BluetoothManager.receivers.forEachIndexed { index, receiverCallBack ->
            receiverCallBack.openContinueBluetooth()
        }
    }

    /**
     * 通知蓝牙正在关闭蓝牙
     */
    private fun notifyCloseContinueBluetooth() {
        BluetoothManager.receivers.forEachIndexed { index, receiverCallBack ->
            receiverCallBack.closeContinueBluetooth()
        }
    }

    /**
     * 通知蓝牙未知错误
     */
    private fun notifyOnErrorBluetooth() {
        BluetoothManager.receivers.forEachIndexed { index, receiverCallBack ->
            receiverCallBack.onErrorBluetooth()
        }
    }
}